﻿Namespace = new Object();
Namespace.register = function (fullname) {
    try {
        var nsArray = fullname.split(".");
        var strNS = "";
        var strEval = "";
        for (var i = 0; i < nsArray.length; i++) {
            if (strNS.length > 0)
                strNS += ".";
            strNS += nsArray[i];
            strEval += " if(typeof(" + strNS + ") =='undefined') " + strNS + " = new Object(); ";
        }
        if (strEval != "") eval(strEval);
    } catch (e) { alert(e.message); }
};
Namespace.register("KevinShop.Common");
Namespace.register("KevinShop.Common.Ajax");
Namespace.register("KevinShop.Common.Loading");
/*
KevinShop = new Object();
KevinShop.Common = new Object();
KevinShop.Common.Ajax = new Object();
*/
/*延迟执行方法,1000=second*/
KevinShop.Common.DelayRun = function (code, time) {
    setTimeout(code, time);
};

KevinShop.Common.Loading.show = function (notautohide) {
    if ($.mobile) {
        $.mobile.loadingMessageTextVisible = true;
        $.mobile.showPageLoadingMsg('a', "处理中...");
        if (!notautohide)
            KevinShop.Common.DelayRun("KevinShop.Common.Loading.hide()", 3000);
    }
    else if ($('.ui-loader')) {
        $('.ui-loader').addClass('ui-loading');
        if (!notautohide)
            KevinShop.Common.DelayRun("KevinShop.Common.Loading.hide()", 3000);
    }
};
KevinShop.Common.Loading.hide = function () {
    if ($.mobile) {
        $.mobile.hidePageLoadingMsg();
    }
    else if ($('.ui-loader')) {
        $('.ui-loader').removeClass('ui-loading');
    }
};

var paramString2obj = function (serializedParams, obj) {
    function evalThem(str) {
        var attributeName = str.split("=")[0];
        var attributeValue = str.split("=")[1];
        if (!attributeValue) {
            return;
        }

        var array = attributeName.split(".");
        for (var i = 1; i < array.length; i++) {
            var tmpArray = Array();
            tmpArray.push("obj");
            for (var j = 0; j < i; j++) {
                tmpArray.push(array[j]);
            };
            var evalString = tmpArray.join(".");
            // alert(evalString);
            if (!eval(evalString)) {
                eval(evalString + "={};");
            }
        };

        eval("obj." + attributeName + "='" + attributeValue + "';");

    };

    var properties = serializedParams.split("&");
    for (var i = 0; i < properties.length; i++) {
        evalThem(properties[i]);
    };

    return obj;
};

/****从form中读取信息，构造到JSON上
因为从form序列化为JSON，是key,value形式的对象，
通过这个方法进行form和实体对象的mapping*****/
KevinShop.Common.FormToObj = function (form, currentObj) {
    var serializedParams = form.serialize();
    var obj = paramString2obj(serializedParams, currentObj);
    return $.toJSON(obj);
};

/****解析json 字符串*****/
KevinShop.Common.EvalJSON = function (src) {
    if (typeof JSON === 'object' && JSON.parse) {
        return $.evalJSON(src);
    }
    else {
        return eval('(' + src + ')');
    }
};

/****将对象序列化为JSON字符串*****/
KevinShop.Common.ToJSON = function (obj) {
    return $.toJSON(obj);
};

/****jQuery 扩展序列化和反序列化方法*****/
jQuery.extend(
 {
     /**
     * @see  将json字符串转换为对象
     * @param   json字符串
     * @return 返回object,array,string等对象
     */
     evalJSON: function (strJson) {
         return eval("(" + strJson + ")");
     }
 });
jQuery.extend(
{
    /**
    * @see  将javascript数据类型转换为json字符串
    * @param 待转换对象,支持object,array,string,function,number,boolean,regexp
    * @return 返回json字符串
    */
    toJSON: function (object) {
        var type = typeof object;
        if ('object' == type) {
            if (Array == object.constructor)
                type = 'array';
            else if (RegExp == object.constructor)
                type = 'regexp';
            else
                type = 'object';
        }
        switch (type) {
            case 'undefined':
            case 'unknown':
                return;
                break;
            case 'function':
            case 'boolean':
            case 'regexp':
                return object.toString();
                break;
            case 'number':
                return isFinite(object) ? object.toString() : 'null';
                break;
            case 'string':
                return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g,
      function () {
          var a = arguments[0];
          return (a == '\n') ? '\\n' :
                      (a == '\r') ? '\\r' :
                      (a == '\t') ? '\\t' : ""
      }) + '"';
                break;
            case 'object':
                if (object == null) return 'null';
                var results = [];
                for (var property in object) {
                    var value;
                    if (object[property] == null)
                        value = 'null';
                    else
                        value = jQuery.toJSON(object[property]);
                    if (value !== undefined)
                        results.push(jQuery.toJSON(property) + ':' + value);
                }
                return '{' + results.join(',') + '}';
                break;
            case 'array':
                var results = [];
                for (var i = 0; i < object.length; i++) {
                    var value = jQuery.toJSON(object[i]);
                    if (value !== undefined) results.push(value);
                }
                return '[' + results.join(',') + ']';
                break;
        }
    }
});

/***Ajax help***/
KevinShop.Common.Ajax.Get = function (url, callback, isJson) {
    var loadMark = KevinShop.Common.Loading;
    if (isJson || isJson == null || isJson == 'undefined') {
        contentType = "application/json; charset=utf-8";
    } else {
        contentType = "application/x-www-form-urlencoded; charset=utf-8";
    }
    $.ajax({
        type: "get",
        url: url,
        beforeSend: function (XMLHttpRequest) {
            loadMark.show();
        },
        success: callback,
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
            loadMark.hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //请求出错处理
            //alert(textStatus);
            loadMark.hide();
        }
    });
};

KevinShop.Common.Ajax.Post = function (url, data, callback, isJson) {
    var loadMark = KevinShop.Common.Loading;
    if (isJson || isJson == null || isJson == 'undefined') {
        contentType = "application/json; charset=utf-8";
    } else {
        contentType = "application/x-www-form-urlencoded; charset=utf-8";
    }
    $.ajax({
        type: "post",
        url: url,
        data: data,
        contentType: contentType,
        beforeSend: function (XMLHttpRequest) {
            loadMark.show();
        },
        success: callback,
        complete: function (XMLHttpRequest, textStatus) {
            //HideLoading();
            loadMark.hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //请求出错处理
            //alert(textStatus);
            loadMark.hide();
        }
    });
};


//MessageBox
Namespace.register("KevinShop.MessageBox");
KevinShop.MessageBox = {
    Alert: function (msg, title) {
        if (title == null || title == 'undefined') {
            title = "温馨提示";
        }
        swal({
            title: msg,
            confirmButtonColor: '#095E37'
        });
        //alert(msg);
    },
    Error: function (msg, title) {
        if (title == null || title == 'undefined') {
            title = "错误";
        }
        swal({
            title: title,
            text: msg,
            timer: 2000,
            confirmButtonColor: '#095E37'
        });
        //alert(msg);

    },
    Warning: function (msg, title) {
        if (title == null || title == 'undefined') {
            title = "提醒";
        }
        swal({
            title: title,
            text: msg,
            type: "warning",
            confirmButtonColor: '#095E37'
        });
        //swal(title, msg, "warning");

    },
    Success: function (msg, title) {
        if (title == null || title == 'undefined') {
            title = "温馨提示";
        }
        swal({
            title: title,
            text: msg,
            confirmButtonColor: '#095E37'
        });
        //alert(msg);
    },
    Confirm: function (msg, title, fn) {
        if (title == null || title == 'undefined') {
            title = "确认";
        }
        swal({
            title: title,
            text: msg,
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false
        },
         function (isConfirm) {
             fn(isConfirm);
         });

        //confirm(msg, fn);
        //return false;
    }
};


//trim function
/**
var myString = " hello my name is ";
alert("*"+myString.trim()+"*");
alert("*"+myString.ltrim()+"*");
alert("*"+myString.rtrim()+"*");
**/
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
};
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
};
/*************************************数字的验 证*****************************************/
/**
* 检查输入的一串字符是否全部是数字
* 输入:str 字符 串
* 返回:true 或 flase; true表示为数字
*/
function checkNum(str) {
    return str.match(/\D/) == null;
}

/**
* 检查输入的一串字符是否为小数
* 输入:str 字符串
* 返 回:true 或 flase; true表示为小数
*/
function checkDecimal(str) {
    if (str.match(/^-?\d+(\.\d+)?$/g) == null) {
        return false;
    }
    else {
        return true;
    }
}
/**
* 检查输入的一串字符是否为整型数据
* 输入:str 字 符串
* 返回:true 或 flase; true表示为小数
*/
function checkInteger(str) {
    if (str.match(/^[-+]?\d*$/) == null) {
        return false;
    }
    else {
        return true;
    }
}
/**
* 检查输入的一串字符是否为整型数据
* 输入:str 字 符串
* 返回:true 或 flase; true表示为小数
*/
function checkMail(str) {
    if (str.search(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/) == -1) {
        return false;
    }
    else {
        return true;
    }
}
function isDate(str) {
    str = str.match(/^\d{4}-((0[1-9]{1})|([1-9]{1})|(1[0-2]{1}))-((0[1-9]{1})|([1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1}))$/);
    if (str == null) {
        return false;
    } else if (str[1] > 23 || str[3] > 59 || str[4] > 59) {
        return false
    } else {
        return true;
    }
}
/****************************************************/
//功能：过滤非法字符
//说明：keypress事件时使用
/****************************************************/
function surnam_keypress(event) {
    //非法字符集
    var codes = "<>/#%'^&*~?+ ~`,/;[]\{}|";
    //事件
    var e = event || window.event;
    //打印字符码
    var code = e.charCode || e.keyCode;
    //功能按键时直接返回
    if (e.charCode == 0) return true;
    //ctr和alt直接返回
    if (e.ctrlKey || e.altKey) return true;
    //ASCII字符
    if (code < 32) return true;
    //字符码转为字符
    var c = String.fromCharCode(code);
    //如果有非法字符则不打印
    if (codes.indexOf(c) != -1) {
        return false;
    }
    else {
        return true;
    }
}
/****************************************************/
//功能：过滤非法字符
//说明：onchange、keyup事件时使用
/****************************************************/
function surnam_keyup(text) {
    //控件值
    var textvalue = text.value;
    //非法字符集
    var codes = "<>/#%'^&*~?+ ~`,/;[]\{}|";
    //非法字符数组
    var codearray = codes.split("");
    //循环替换非法字符
    for (i = 0; i < codearray.length; i++) {
        while (textvalue.indexOf(codearray[i]) != -1) {
            textvalue = textvalue.replace(codearray[i], "");
        }
    }
    //重新给控件赋值
    text.value = textvalue;

}